package servlet;

import dao.ArticleDao;
import dao.LikeDao;
import dao.daoimpl.ArticleDaoImpl;
import dao.daoimpl.LikeDaoImpl;
import bean.Article;
import bean.Like;
import bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name="AddLikeServlet",urlPatterns = "/AddLikeServlet")
public class AddLikeServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");/*防止乱码*/
        int articleId=Integer.parseInt(request.getParameter("addLikeArticleId"));/*博客id*/
        User user=(User)request.getSession().getAttribute("user");/*获取用户*/
        LikeDao likeDao=new LikeDaoImpl();
        ArticleDao articleDao=new ArticleDaoImpl();
        if(likeDao.addLike(new Like(articleId,user.getAccount()))){
            System.out.println("用户点赞成功");
            try {
                for(Article article:articleDao.getLikedArticles(user)){
                    System.out.println(article.getTitle());
                }
                request.getSession().setAttribute("userLikes",articleDao.getLikedArticles(user));/*返回*/
                request.getSession().setAttribute("userLiked",likeDao.getLikes(user));
            } catch (SQLException sqlException) {
                sqlException.printStackTrace();
            }
        }else{
            System.out.println("用户点赞失败");
        }

    }
}
